﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DictionariesManager.cs" company="CodePlex">
//   The MIT License
//   Copyright (c) 2013 Julien Blin
//   
//   Permission is hereby granted, free of charge, to any person obtaining a copy
//   of this software and associated documentation files (the "Software"), to deal
//   in the Software without restriction, including without limitation the rights
//   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//   copies of the Software, and to permit persons to whom the Software is
//   furnished to do so, subject to the following conditions:
//   
//   The above copyright notice and this permission notice shall be included in
//   all copies or substantial portions of the Software.
//   
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//   THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace UCodeFirst.Dictionaries
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Globalization;
    using System.Linq;
    using System.Resources;

    using Umbraco.Core;
    using Umbraco.Core.Logging;
    using Umbraco.Core.Models;

    /// <summary>
    /// Manager responsible for synchronizing dictionaries and languages.
    /// </summary>
    public class DictionariesManager : UCodeFirstManagerBase
    {
        /// <summary>
        /// The regular expression to capture dictionaries as embedded resources.
        /// </summary>
        private const string RegexDictionaryResources = ".*\\.(?<culture>[a-z]{2}\\-[a-z]{2})\\.resources";

        /// <summary>
        /// Returns <see cref="ManagerPriorities.Dictionaries"/>.
        /// </summary>
        public override int Priority
        {
            get
            {
                return ManagerPriorities.Dictionaries;
            }
        }

        /// <summary>
        /// All the managers <see cref="UCodeFirstManagerBase.Synchronize"/> methods will run after all the managers <see cref="UCodeFirstManagerBase.BeforeSynchronization"/> method have run,
        /// <b>only</b> if the synchronization happens.<br />
        /// They run in the order specified by the <see cref="UCodeFirstManagerBase.Priority"/>.
        /// </summary>
        /// <param name="httpApplication">
        ///     The <see cref="UmbracoApplicationBase"/>.
        /// </param>
        /// <param name="applicationContext">
        ///     The <see cref="ApplicationContext"/>.
        /// </param>
        public override void Synchronize(UmbracoApplicationBase httpApplication, ApplicationContext applicationContext)
        {
            var dictResources = TypesScanner.GetResourcesInBin(RegexDictionaryResources).ToList();
            var localizationService = ApplicationContext.Current.Services.LocalizationService;

            LogHelper.Debug<DictionariesManager>(Resources.FoundNDictResources.InvariantFormat(dictResources.Count));

            // Synchronize languages
            var allLanguages = localizationService.GetAllLanguages().ToList();
            foreach (var dictResource in dictResources)
            {
                try
                {
                    var cultureInfo = CultureInfo.CreateSpecificCulture(dictResource.Match.Groups["culture"].Value);
                    var language = allLanguages.FirstOrDefault(x => x.CultureInfo.Equals(cultureInfo));

                    if (language == null)
                    {
                        language = new Language(cultureInfo.Name);
                        localizationService.Save(language, UCodeFirstConfig.GetUser().Id);
                        allLanguages.Add(language);
                    }
                }
                catch (Exception ex)
                {
                    throw new UCodeFirstException(Resources.ErrorWhileSynchronizing.InvariantFormat(dictResource.ResourceName), ex);
                }
            }

            // Synchronize dict items
            var dictItemsToSave = new List<IDictionaryItem>();
            foreach (var dictResource in dictResources)
            {
                try
                {
                    LogHelper.Debug<DictionariesManager>(Resources.Synchronizing.InvariantFormat(dictResource.ResourceName));

                    var language = allLanguages.First(x => x.IsoCode.ToLowerInvariant().InvariantEquals(dictResource.Match.Groups["culture"].Value.ToLowerInvariant()));

                    using (var reader = new ResourceReader(dictResource.Assembly.GetManifestResourceStream(dictResource.ResourceName)))
                    {
                        foreach (var res in reader.OfType<DictionaryEntry>())
                        {
                            var mustBeSaved = false;
                            var dictItem = dictItemsToSave.FirstOrDefault(x => x.ItemKey.InvariantEquals(res.Key.ToString()))
                                           ?? localizationService.GetDictionaryItemByKey(res.Key.ToString());

                            if (dictItem == null)
                            {
                                dictItem = new DictionaryItem(res.Key.ToString());
                                dictItemsToSave.Add(dictItem);
                            }

                            var translations = dictItem.Translations.ToList();
                            var translation = translations.FirstOrDefault(x => x.Language.CultureInfo.Equals(language.CultureInfo));
                            if (translation == null)
                            {
                                translation = new DictionaryTranslation(language, res.Value.ToString());
                                translations.Add(translation);
                                mustBeSaved = true;
                            }
                            else
                            {
                                if (string.Compare(translation.Value, res.Value.ToString(), language.CultureInfo, CompareOptions.None) != 0)
                                {
                                    translation.Value = res.Value.ToString();
                                    mustBeSaved = true;
                                }
                            }

                            if (mustBeSaved)
                            {
                                dictItem.Translations = translations;
                                if (!dictItemsToSave.Any(x => x.ItemKey.InvariantEquals(res.Key.ToString())))
                                {
                                    dictItemsToSave.Add(dictItem);
                                }
                            }
                        }
                    }

                    LogHelper.Debug<DictionariesManager>(Resources.Synchronized.InvariantFormat(dictResource.ResourceName));
                }
                catch (Exception ex)
                {
                    throw new UCodeFirstException(Resources.ErrorWhileSynchronizing.InvariantFormat(dictResource.ResourceName), ex);
                }
            }

            dictItemsToSave.ForEach(x =>
                {
                    try
                    {
                        localizationService.Save(x, UCodeFirstConfig.GetUser().Id);
                    }
                    catch (Exception ex)
                    {
                        throw new UCodeFirstException(Resources.ErrorWhileSynchronizing.InvariantFormat(x.ItemKey), ex);
                    }
                });

            LogHelper.Debug<DictionariesManager>(Resources.SynchronizedNDictResources.InvariantFormat(dictResources.Count));
        }
    }
}
